package com.ftg.learn.framework.mybatis.chapter03.util;

import com.ftg.learn.framework.mybatis.chapter01.DemoMapper;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * @author 布衣
 */
public class MybatisUtil {

    SqlSession sqlSession = null;
    SqlSessionFactory sqlSessionFactory = null;

    /**
     * 初始化配置
     * @return
     */
    public Configuration initConfiguration(){
//        配置文件
        Configuration c = new Configuration();
        MysqlDataSource d = new MysqlDataSource();
        d.setUser("root");
        d.setPassword("123456");
        d.setURL("jdbc:mysql://localhost:3306/dbnd");
        Environment env = new Environment("dev", new JdbcTransactionFactory(), d);
        c.setEnvironment(env);

        c.addMappers("com.ftg.learn.framework.mybatis.chapter03.mapper");

        //settings
        c.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        return c;
    }

    public SqlSessionFactoryBuilder initSqlSessionFactoryBuilder(){
        return new SqlSessionFactoryBuilder();
    }

    public SqlSessionFactory initSqlSessionFactory(){
        if(sqlSessionFactory == null){
            sqlSessionFactory = initSqlSessionFactoryBuilder().build(initConfiguration());
        }
        return sqlSessionFactory;
    }

    public SqlSession initSqlSession(){
        if(sqlSession == null){
            sqlSession = initSqlSessionFactory().openSession();
        }
        return sqlSession;
    }

    public SqlSession getSession(){
        initSqlSession();
        return sqlSession;
    }



}
